/*
  学习目标：使用subscribe监听数据的变化
  作用: 监听仓库数据的变化
  语法: const 解除监听的函数 = subscribe(() => { 回调函数内,可以获取到每次数据更新后的值 })
*/

import { legacy_createStore as createStore } from 'redux';

const store = createStore(function (state = { count: 100, msg: 'hello React' }, action) {
  if (action.type === 'add') {
    return {
      ...state,
      count: state.count + 1,
    };
  }

  if (action.type === 'des') {
    return {
      ...state,
      count: state.count - 1,
    };
  }

  return state;
});
store.dispatch({ type: 'add' });
store.dispatch({ type: 'add' });

// 💥 开启监听之后的dispatch才会被监听到
const unFn = store.subscribe(() => {
  console.log('store.getState()  ----->  ', store.getState().count);
});

store.dispatch({ type: 'add' });
store.dispatch({ type: 'des' });
// 💥 取消监听之前的dispatch才会被监听到
unFn();
